import React, { useState, useRef } from 'react';
import { View, StyleSheet, TouchableOpacity, Pressable, GestureResponderEvent } from 'react-native';

type Dot = {
  id: number;
  x: number;
  y: number;
};

// 箭靶组件 - 由多个同心圆组成，支持点击记录位置和长按瞄准功能
const VectorGraphic = ({ onDotPlaced }: { onDotPlaced?: (dot: Dot) => void }) => {
  const [dots, setDots] = useState<Dot[]>([]);
  const [isAiming, setIsAiming] = useState(false);
  const [aimPosition, setAimPosition] = useState({ x: 0, y: 0 });
  const containerRef = useRef(null);
  const targetSize = 200; // 箭靶大小
  const aimSize = 50; // 瞄准视图大小

  const handleTargetPress = (event: GestureResponderEvent) => {
    const { locationX, locationY } = event.nativeEvent;

    // 创建一个新的点，使用相对坐标
    const newDot = {
      id: Date.now(), // 使用时间戳作为唯一ID
      x: locationX,
      y: locationY,
    };

    // 添加到点数组中
    setDots(prevDots => [...prevDots, newDot]);

    // 如果有回调函数，通知父组件
    if (onDotPlaced) {
      onDotPlaced(newDot);
    }
  };

  // 限制瞄准位置在箭靶范围内
  const constrainAimPosition = (x: number, y: number) => {
    console.log('x ',x,'y',y);
    // return {
    //   x: x,
    //   y: y,
    // };
    // 计算瞄准视图的边界（确保瞄准视图完全在箭靶内）
    // const minX = aimSize / 2;
    // const maxX = targetSize - aimSize / 2;
    // const minY = aimSize / 2;
    // const maxY = targetSize - aimSize / 2;
const minX = -aimSize / 2;
    const maxX = targetSize + aimSize / 2;
    const minY = -aimSize / 2 +5;
    const maxY = targetSize + aimSize / 2 -5;
    // 限制坐标在有效范围内
    const constrainedX = Math.max(minX, Math.min(maxX, x));
    const constrainedY = Math.max(minY, Math.min(maxY, y));
    console.log('x2 ',constrainedX,'y2',constrainedY);

    return { x: constrainedX, y: constrainedY };
  };

  const handleLongPressIn = (event: GestureResponderEvent) => {
    console.log('handleLongPressIn ');
    const constrainedPosition = constrainAimPosition(
      event.nativeEvent.locationX,
      event.nativeEvent.locationY - 30
    );
    setIsAiming(true);
    setAimPosition(constrainedPosition);
  };

  // 处理触摸移动（更新瞄准镜位置）
  const handleTouchMove = (event: GestureResponderEvent) => {
    if (!isAiming) return;
    const constrainedPosition = constrainAimPosition(
      event.nativeEvent.locationX,
      event.nativeEvent.locationY - 30
    );
    setAimPosition(constrainedPosition);
  };

  // 处理触摸结束（隐藏瞄准镜）
  const handleTouchEnd = () => {
    console.log('handleTouchEnd ');
    if (!isAiming) return;

    setIsAiming(false);
    let newDot = {
      id: Date.now(), // 使用时间戳作为唯一ID
      x: aimPosition.x,
      y: aimPosition.y,
    };
    setDots(prevDots => [...prevDots, newDot]);

    // 如果有回调函数，通知父组件
    if (onDotPlaced) {
      onDotPlaced(newDot);
    }
  };

  const clearDots = () => {
    setDots([]);
  };

  return (
    <View style={styles.container} ref={containerRef}>
      <Pressable
        style={styles.targetContainer}
        onPress={handleTargetPress}
        // 触摸开始（长按起点）
        onLongPress={handleLongPressIn}      // 长按触发（确保瞄准镜显示）
        // onPressOut={handlePressOut}      // 触摸结束（隐藏瞄准镜）
        onTouchEnd={handleTouchEnd}
        onTouchMove={handleTouchMove}    // 触摸移动（更新位置）
        delayLongPress={1000}
      >
        <View pointerEvents='none'>
          {/* 最外层圆 - 白色 */}
          <View style={[styles.circle, styles.outerCircle]} />
          {/* 第二层圆 - 黑色 */}
          <View style={[styles.circle, styles.secondCircle]} />
          {/* 第三层圆 - 蓝色 */}
          <View style={[styles.circle, styles.thirdCircle]} />
          {/* 第四层圆 - 红色 */}
          <View style={[styles.circle, styles.fourthCircle]} />
          {/* 最内层圆 - 黄色 */}
          <View style={[styles.circle, styles.innerCircle]} />

          {/* 显示所有点 */}
          {dots.map(dot => (
            <View
              key={dot.id}
              style={[
                styles.dot,
                {
                  left: dot.x - 5, // 调整位置使点居中
                  top: dot.y - 5,
                }
              ]}
            />
          ))}

          {/* 瞄准视图 */}
          {isAiming && (
            <View
              style={[
                styles.aimView,
                {
                  left: aimPosition.x - aimSize / 2, // 调整位置使瞄准视图居中
                  top: aimPosition.y - aimSize / 2,
                }
              ]}
            >
              <View style={styles.aimCircle} />
              <View style={styles.aimCrosshairHorizontal} />
              <View style={styles.aimCrosshairVertical} />
            </View>
          )}
        </View>
      </Pressable>

      {/* 清除按钮 */}
      {dots.length > 0 && (
        <TouchableOpacity style={styles.clearButton} onPress={clearDots}>
          <View style={styles.clearButtonTextContainer}>
            <View style={styles.clearButtonX} />
            <View style={[styles.clearButtonX, styles.clearButtonXRotated]} />
          </View>
        </TouchableOpacity>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: 250,
    height: 250,
    justifyContent: 'center',
    alignItems: 'center',
    padding:25,
    // backgroundColor: '#666',
    borderWidth:1,
    borderColor:'#000',
  },
  targetContainer: {
    width: 200,
    height: 200,
    position: 'relative',
    // backgroundColor: 'yellow',

  },
  circle: {
    position: 'absolute',
    borderRadius: 100,
  },
  outerCircle: {
    width: 200,
    height: 200,
    backgroundColor: '#ffffff',
    borderWidth: 2,
    borderColor: '#000000',
  },
  secondCircle: {
    width: 160,
    height: 160,
    backgroundColor: '#000000',
    left: 20,
    top: 20,
  },
  thirdCircle: {
    width: 120,
    height: 120,
    backgroundColor: '#3498db',
    left: 40,
    top: 40,
  },
  fourthCircle: {
    width: 80,
    height: 80,
    backgroundColor: '#e74c3c',
    left: 60,
    top: 60,
  },
  innerCircle: {
    width: 40,
    height: 40,
    backgroundColor: '#f1c40f',
    left: 80,
    top: 80,
  },
  dot: {
    position: 'absolute',
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: '#2ecc71', // 绿色点
    borderWidth: 1,
    borderColor: '#fff',
    zIndex: 10,
  },
  aimView: {
    position: 'absolute',
    width: 50,
    height: 50,
    zIndex: 20,
  },
  aimCircle: {
    width: 32,
    height: 32,
    borderRadius: 16,
    borderWidth: 2,
    left: 9,
    top: 9,
    borderColor: '#ff0000',
    position: 'absolute',
  },
  aimCrosshairHorizontal: {
    position: 'absolute',
    width: 50,
    height: 2,
    backgroundColor: '#ff0000',
    top: 24,
  },
  aimCrosshairVertical: {
    position: 'absolute',
    width: 2,
    height: 50,
    backgroundColor: '#ff0000',
    left: 24,
  },
  clearButton: {
    position: 'absolute',
    right: -30,
    top: -30,
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: '#e74c3c',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 10,
  },
  clearButtonTextContainer: {
    width: 12,
    height: 12,
    position: 'relative',
  },
  clearButtonX: {
    position: 'absolute',
    width: 12,
    height: 2,
    backgroundColor: '#fff',
    top: 5,
  },
  // clearButtonXRotated: {
  //   transform: [{ rotate: '90deg' }],
  // },
});

export default VectorGraphic;